package org.consul.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

/**
 * 消费者
 */
@RestController
public class ConsumerController {

    @Autowired
    private FeignService consumerService;
    
    @Autowired
    RestTemplate restTemplate;
    
    @Autowired 
    private OpenFeignClient openFeignClient;
    
    @Value("${spring.cloud}")
    private String config;

    @GetMapping("/config")
    public String getConfig() {
        return config;
    }
    
    @GetMapping("/consumer")
    @HystrixCommand(fallbackMethod = "hiError")
    public String getProducer(){

        return consumerService.producer();
    }
    
    @GetMapping("/test")
    @HystrixCommand(fallbackMethod = "hiError")
    public String test(){
    	return restTemplate.getForObject("http://consul-producer/producer", String.class);
        //return "test";
    }
    
    
    @GetMapping("/getServices")
    @HystrixCommand(fallbackMethod = "feinError")
    public Result getServices(){
    	return openFeignClient.getServices() ;
    }
    
    
    public String hiError() {
        return "hi,sorry,error! [HystrixCommand]";
    }
   
    public Result feinError() {
        return new Result(false,"hi,sorry,error! [HystrixCommand]");
    }
    
    @FeignClient("consul-service")
	interface OpenFeignClient {
		@RequestMapping(value = "/services", method = RequestMethod.GET)
		Result getServices();
	}
}